<?php

namespace app\api\controller\yalimedia;

use addons\yalimedia\library\AlibabaCloundHelper;
use app\admin\model\yalimedia\course\Content;
use app\admin\model\yalimedia\course\Contentlog;
use app\admin\model\yalimedia\Order;
use app\common\controller\Api;
use Yansongda\Pay\Exceptions\GatewayException;

use app\common\model\CourseQuestion as CourseQuestionModel;
// use app\common\model\Question as QuestionModel;

use addons\exam\model\QuestionModel;

use app\common\services\UrlService;

use app\common\model\Config as ConfigModel;

use think\Config;
use app\common\services\CourseService;

use app\common\model\YalimediaQuestionLog as LogModel;

/**
 * 课程接口
 */
class Course extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['categories','info'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 获取课程详情
     * @throws \think\Exception
     */
    public function info()
    {
        $keyword = $this->request->post('keyword');
        $cid = $this->request->post('cid');
        $page = $this->request->post('page');
        $limit = $this->request->post('num',10);

        $where = [];
        if($keyword){
            $where['title'] = ['like','%'.$keyword.'%'];
        }
        if($cid){
            $where['cate_id'] = $cid;
        }
        $subject = new CourseService;
        $data = $subject->getCourseList($this->auth->id,$where,$page,$limit);

        foreach($data['data'] as &$v){
         
            $v['cover'] = UrlService::getFileUrl($v['cover']);
        }
        $this->success('请求成功', $data);
    }
    /**
     * 获取我的课程
     * @throws \think\Exception
     */
    public function myinfo()
    {
        $keyword = $this->request->post('keyword');
        $page = $this->request->post('page');
        $limit = $this->request->post('num',10);

        $where = [];
        if($keyword){
            $where['title'] = ['like','%'.$keyword.'%'];
        }

        $subject = new CourseService;
        $data = $subject->getMyCourseList($this->auth->id,$where,$page,$limit);

        foreach($data['data'] as &$v){

            $v['cover'] = UrlService::getFileUrl($v['cover']);
        }
        $this->success('请求成功', $data);
    }
    /**
     * 获取热门课程列表
     * @throws \think\Exception
     */
    public function hot()
    {
        $page  = $this->request->post('page');
        $limit = $this->request->post('limit');
        
        $subject = new CourseService;
        $data = $subject->getHotCourseList($page,$limit);
        foreach($data['data'] as &$v){
            $v['cover'] = $this->request->domain().$v['cover'];
        }
        $this->success('请求成功', $data);
    }


    /*
     * 课程列表
     */
    public function index(){
        $id = $this->request->post('id');

        $course = new CourseService;
        $courseInfo = $course->getCourseInfo($id,$this->auth->id);
        if(empty($courseInfo)){
            $this->success($course->error,[]);
        }
        $this->success('请求成功', $courseInfo);
    }


    /**
     * 获取章节信息
     *
     * @return void
     */
    public function getList(){

        $type = $this->request->post('type');
        if(empty($type)){
            return $this->error('参数错误');
        }
        
        $site = Config::get('site');
        switch ($type) {
            case 1:
                // 900句学习
                $id = $site['word_id'];
                break;
            case 2:
                // 模拟通话
                $id = $site['call_id'];
                break;
            case 3:
                // 阅读学习
                $id = $site['read_id'];
                break;
            case 4:
                // 听力学习
                $id = $site['hearing_id'];
                break;
            case 5:
                // 雅思英语
                $id = $site['ysyy'];
                break;
            case 6:
                // 雅思英语
                $id = $site['qp_english'];
                break;
            case 7:
                // 雅思英语
                $id = $site['opi'];
                break;
            default:
                # code...
                break;
        }

        $course = new CourseService;
        $courseInfo = $course->getCourseInfo($id,$this->auth->id);
        if(empty($courseInfo)){
            $this->success($course->error,[]);
        }
        $this->success('请求成功', $courseInfo);
    }

 

    /**
     * 收藏/取消收藏课程
     */
    public function fav(){
        $id = $this->request->post('id');
        $fav = new \addons\yalimedia\service\Fav();
        $return = $fav->act(1,$id,$this->auth->id);

        $this->success('请求成功',$return);
    }

    /**
     * 获取分类
     */
    public function categories(){
        $model = new \app\admin\model\yalimedia\course\Category();
        $categorylist = collection($model->field("id,name")->where(['pid'=>0,'status'=>'normal'])->order("weigh desc")->select())->toArray();
        // foreach($categorylist as &$v){
        //     $model = new \app\admin\model\yalimedia\course\Category();
        //     $childlist = collection($model->field("id,name")->where(['pid'=>$v['id'],'status'=>'normal'])->order("weigh asc,id asc")->select())->toArray();
        //     $v['child'] = $childlist;
        // }
        $this->success('请求成功',$categorylist);
    }

    /**
     * 获取内容
     */
    public function content(){
        
        $content_id = $this->request->post("id");
        $courseContentModel = new Content();
        if(!$content = $courseContentModel->where(['id'=>$content_id])->field('id,course_id,unit_id,type,title,media_id,content,create_time')->find()){
            $this->error("当前内容不存在");
        }

        $courseModel = new \app\admin\model\yalimedia\Course();
        if(!$courseInfo = $courseModel->where(['status'=>1,'id'=>$content['course_id']])->find()){
            $this->error("当前课程不存在");
        }

        //获取用户是否是vip
        // $isVip = \addons\yalimedia\service\User::isVip($this->auth->id);

        // if(($isVip && $courseInfo['vip_price']>0 ) || (!$isVip && $courseInfo['price']>0)){
        //     /**
        //      * 是否购买
        //      */
        //     $order = new \app\admin\model\yalimedia\Order();
        //     if(!$order->where(['type'=>1,'status'=>2,'item_id'=>$courseInfo['id'],'user_id'=>$this->auth->id])->find()){
        //         $this->error("您还未购买当前课程");
        //     }
        // }
        
        
        
        // //记录学习记录
        // $contentLogModel = new Contentlog();
        // if($contentLog = $contentLogModel->where(['content_id'=>$content['id'],'user_id'=>$this->auth->id])->find()){
        //     $contentLog->save(['last_time'=>time()]);
        // }else{
        //     $contentLogModel->save([
        //         'course_id'=>$content['course_id'],
        //         'user_id'=>$this->auth->id,
        //         'content_id'=>$content['id'],
        //         'begin_time'=>time(),
        //         'last_time'=>time(),
        //     ]);
        // }
        
        if($content['type'] == 1){
            
            // 视频素材
            $model = new \app\admin\model\yalimedia\Category();
            $result = $model->where('id',$content['media_id'])->find();
            $content['play_url'] = UrlService::getFileUrl($result['url']);
        }
        $this->success("请求成功",$content);
        
        // switch ($content['type']){
        //     case "1":
        //     case "3":
        //         $result = AlibabaCloundHelper::instance()->GetPlayInfo($content['media_id']);
            
        //         if($result){
        //             $data['PlayURL'] =$result['PlayInfoList']['PlayInfo'][0]['PlayURL'] ;
        //             $this->success("请求成功",$data);
        //         }else{
        //             $this->error("请求失败123");
        //         }
                
                
        //         break;
        //     case "2":
        //         $this->success("请求成功",$content['content']);
        //         break;
        // }
    }

    /**
     * 购买课程
     */
    public function buy(){
        $id = $this->request->post('id');
        $course = new CourseService;
        $courseInfo = $course->getCourseInfo($id,$this->auth->id);
        if(empty($courseInfo)){
            $this->error($course->error);
        }
        $course = new \addons\yalimedia\service\Tool();
        $order_no = $course->create_sn();

        $orderModel = new Order();
        if($orderModel->save([
            'order_no'=>$order_no,
            'user_id'=>$this->auth->id,
            'type'=>1,
            'item_id'=>$id,
            'price'=>\addons\yalimedia\service\User::isVip($this->auth->id)?$courseInfo['vip_price']:$courseInfo['price']
        ])){
            try {
                $wechatUser = \app\admin\model\yalimedia\Wechat::get(['user_id' => $this->auth->id,'type' =>'mp']);
                $params = [
                    'amount'=>\addons\yalimedia\service\User::isVip($this->auth->id)?$courseInfo['vip_price']:$courseInfo['price'],
                    'orderid'=>$order_no,
                    'type'=>"wechat",
                    'title'=>$courseInfo['title'],
                    'notifyurl'=>$this->request->domain()."/api/yalimedia/block/notifyx",
                    'returnurl'=>"",
                    'method'=>"mp",
                    'openid'=>$wechatUser['openid'],
                ];
                $info = get_addon_info('epay');
                if(empty($info)){
                    $this->error('请到后台插件管理安装《微信支付宝整合》插件');
                }
                $result = \addons\epay\library\Service::submitOrder($params);
            }catch (GatewayException $e){
                $this->error($e->getMessage());
            }

            $this->success('请求成功',$result);
        }else{
            $this->success('请求失败，请稍后再试');
        }
    }

    /**
     * 获取章节下试题
     *
     * @return void 
     */
    public function list(){

        // 章节ID
        $id  = $this->request->post('id',0);
        if(empty($id)){
            $this->error('参数错误');
        }
        
        $data = collection(CourseQuestionModel::alias('a')->field('a.question_id')->join('exam_question b','a.question_id=b.id')->where('a.cate_id',$id)->select())->toArray();
        if($data){
            $ids = array_column($data,'question_id');
        }else{
            $this->success('请求成功',[]);
        }
  

        // 记录ID[答题记录回显]
        $log_id = $this->request->post('log_id',0);
        $list   = QuestionModel::getQuestion($ids,$id,$this->auth->id,$log_id);
        
        $status = LogModel::where(['course_id'=>$id,'status'=>1,'user_id'=>$this->auth->id])->count();
        $list['status'] = $status > 0 ? 1 : 0;
        $this->success('请求成功',$list);
    }

}
